#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setFixedSize(QSize(ChessWidth,ChesHeight));
    //每一个格子的宽度和高度,和边距的宽度高度相同
    caseWidthX = ChessWidth/LineCount;
    caseWidthY = ChesHeight/LineCount;
    drawChessman = false;
}
MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::paintEvent(QPaintEvent *event)
{
    int borderLeft = ChessWidth/LineCount;
    int borderTop = ChesHeight/LineCount;
    QPainter qPainter(this);

    QPen qPen;
    qPen.setWidth(5);
    qPainter.setPen(qPen);
    for (int var = 1; var < LineCount; ++var) {
        qPainter.drawLine(borderLeft,borderTop*var,ChessWidth-borderLeft,borderTop*var);
        qPainter.drawLine(borderLeft*var,borderTop,borderLeft*var,ChesHeight-borderTop);
    }
    if (drawChessman) {
        //绘制棋子到棋盘的格子棋盘
        qPainter.drawPixmap(indexX*caseWidthX,indexY*caseWidthY,caseWidthX,caseWidthY,QPixmap(":/new/prefix1/resources/chess_PNG8420.png"));
    }
}

void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    QMouseEvent* mouseEvent=(QMouseEvent*)event;
    if (mouseEvent->type() == QEvent::MouseButtonRelease && mouseEvent->button()==Qt::LeftButton)
    {
        int   x = mouseEvent->x();
        int   y = mouseEvent->y();



        if (x<caseWidthX || x>ChessWidth-(caseWidthX)) {
            cout<<"x:超出棋盘范围";
            return;
        }

        if (y<caseWidthY || y>ChesHeight-(caseWidthY)) {
            cout<<"y:超出棋盘范围";
            return;
        }
        //判断坐标属于第几个格子
        indexX = x /caseWidthX;
        indexY = y /caseWidthY;

        indexX= indexX>MaxCaseCount?MaxCaseCount:indexX;
        indexY= indexY>MaxCaseCount?MaxCaseCount:indexY;
        cout<<" ( indexX = "<< indexX <<" , indexY = "<< indexY <<" )";
        drawChessman = true;
        update();

    }
}

